package com.fanping.servlet.user;
import com.alibaba.fastjson.JSONArray;
import com.fanping.pojo.Role;
import com.fanping.pojo.User;
import com.fanping.service.role.RoleService;
import com.fanping.service.role.RoleServiceImpl;
import com.fanping.service.user.UserService;
import com.fanping.service.user.UserServiceImpl;
import com.fanping.util.Constants;
import com.fanping.util.PageSupport;
import com.mysql.jdbc.StringUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//实现servlet复用
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("savepwd") && method !=null){
            this.updatePwd(req,resp);
        }else if(method.equals("pwdmodify") && method !=null){
            this.pwdModify(req,resp);
        }else if (method.equals("query") && method !=null){
            this.query(req,resp);
        }else if(method.equals("getrolelist") && method !=null) {
            this.getRoleList(req, resp);
        }else if(method.equals("add") && method !=null) {
            this.add(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    //修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
        //从session里面拿ID
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String newpassword = req.getParameter("newpassword");
        System.out.println("UserServlet+UserServlet:"+newpassword);
        boolean flag = false;
        if( o !=null && newpassword !=null){
            UserService userService = new UserServiceImpl();
            flag = userService.updatePwd(((User) o).getId(), newpassword);
            if(flag){
                req.setAttribute("message","修改密码成功，请退出，使用新密码登录");
                //密码修改成功移除当前session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else{
                req.setAttribute("message","密码修改失败");
            }
        }else{
            req.setAttribute("message","新密码有问题");
        }
        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //验证旧密码，session中有用户的密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        //从session里面拿ID
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");
        //万能的Map 结果集
        Map<String, String> resultMap = new HashMap<String,String>();
        if(o == null){//session过期
            resultMap.put("result","sessionerror");
        }else if(StringUtils.isNullOrEmpty(oldpassword)){ //输入的密码为空
            resultMap.put("result","error");
        }else{
            String userPassword = ((User) o).getUserPassword();//Session中用户的密码
            if(oldpassword.equals(userPassword)){
                resultMap.put("result","true");
            }else{
                resultMap.put("result","false");
            }
        }
        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            //JSONArray阿里巴巴的工具类，转换格式
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //查询用户列表
    public void query(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String queryUserName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");//从前端获取的
        String pageIndex = req.getParameter("pageIndex");
        System.out.println(pageIndex+"pageIndex1");
        int queryUserRole = 0;
        List<User> userList = null;
        //获取用户列表
        UserServiceImpl userService = new UserServiceImpl();

        //第一次走这个请求，一定是第一页并且页面大小固定
        int pagesize = 5;//可以把这些写到配置文件里，方便后期修改
        int currentPageNo = 1;

        if(queryUserName == null){
            queryUserName="";
        }
        if(temp != null && temp.equals("")){
            queryUserRole = Integer.parseInt(temp);  //给查询赋值
        }
        if(pageIndex != null){
            try {
                currentPageNo = Integer.parseInt(pageIndex);
            } catch (NumberFormatException e) {
                resp.sendRedirect("error.jsp");
            }
        }
        //获取用户总数(分页：上一页和下一页)
        int totalCount = userService.getUserCount(queryUserName, queryUserRole);
        //总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pagesize);
        pageSupport.setTotalPageCount(totalCount);

        int totalPageCount = pageSupport.getTotalPageCount();
        //int totalPageCount = ((int)(totalCount/pagesize))+1;
        //控制首页和尾页
        //如果页面要小于1了就显示第一页的东西
//        System.out.println(currentPageNo+"currentPageNo1");
//        System.out.println(totalPageCount+"totalPageCount1");
        if(currentPageNo < 1){
            currentPageNo = 1;
//            System.out.println("设置");

        }else if(currentPageNo>totalPageCount){ //如果当前的页面大于了最后一页;
//            System.out.println(totalPageCount+"totalPageCount2");
//            System.out.println("2设置");
            currentPageNo = totalPageCount;
        }
//        System.out.println(currentPageNo+"bbbb");
        //currentPageNo = 1;
        //获取用户列表展示
        userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pagesize);
        req.setAttribute("userList",userList);

        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        req.setAttribute("roleList",roleList);
        req.setAttribute("queryUserName",queryUserName);
        req.setAttribute("queryUserRole",queryUserRole);
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);

        //返回前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }
    //用户添加
    private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("add()================");
        String userCode = request.getParameter("userCode");
        String userName = request.getParameter("userName");
        String userPassword = request.getParameter("userPassword");
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String userRole = request.getParameter("userRole");

        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId());

        UserService userService = new UserServiceImpl();
        if(userService.add(user)){
            response.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query");
        }else{
            request.getRequestDispatcher("useradd.jsp").forward(request, response);
        }

    }
    //获取角色列表
    private void getRoleList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Role> roleList = null;
        RoleService roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();
        //把roleList转换成json对象输出
        response.setContentType("application/json");
        PrintWriter outPrintWriter = response.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(roleList));
        outPrintWriter.flush();
        outPrintWriter.close();
    }


}
